<template>
  <div class="order-batch-modal">
    <el-dialog :title="$t('orderBatchModal.' + modalOrderData.action.toLowerCase().replace(' ', '_'))" :visible.sync="modalOrderData.show"
                v-if="modalOrderData.action==='Push' || modalOrderData.batch" class="modal-primary" 
                @open="open" @close='hidden'>
      <div v-if="modalOrderData.batch">
        <!-- Batch Assign -->
        <div v-if="modalOrderData.action=='Batch Assign'">
            <el-row>
                <el-col :md="24">
                    <el-form :model="formModel" :rules="rules" ref="orderWithdrawForm" label-width="180px">
                        <el-form-item
                            :label="$t('orderBatchModal.status')"
                            label-for="basicSelect"
                            label-cols="2"
                            :horizontal="true" label-size="sm"
                            prop="batchOrderStatus">
                            <el-select v-model="formModel.batchOrderStatus" :placeholder="$t('orderBatchModal.select_order_status')" style="width: 100%">
                                <el-option v-for="item in getOptions" :key="item.value" :label="item.label" :value="item.value">
                                    <span style="float: left">{{ item.label }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item  :label="$t('orderBatchModal.notes')" label-cols="2" :horizontal="true" label-size="sm" prop="batchOrderNotes">
                            <el-input type="textarea" :placeholder="$t('orderBatchModal.enter_notes')" :rows="3" :max-rows="6" size="sm" v-model="formModel.batchOrderNotes" @input="onBatchOrderChangeNotes"></el-input>
                            <div style="position: relative;">
                                <div style="position: absolute; bottom: -10px; right: 5px;">{{batchOrderNotesRemaining}} {{$t('orderBatchModal.character')}}</div>
                            </div>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            &nbsp;
            <el-card no-body border-variant="info" :header="$t('orderBatchModal.continue_assign')" align="left">
                <el-row  v-for="pushOrder in modalOrderData.batchOrder" v-bind:key="pushOrder.id">
                  <el-col :span="1" class="flex-display"><i :class="!orderFinished.includes(pushOrder.status) ? 'el-icon-success': 'el-icon-error'"></i></el-col>
                  <el-col :span="8" class="flex-display"><div class="grid-content bg-purple">{{pushOrder.id}}</div></el-col>
                  <el-col :span="6" class='flex-display'><div class="grid-content bg-purple">{{OrderStatusArray[pushOrder.status]}}</div></el-col>
                  <el-col :span="2" class='flex-display'><div class="grid-content bg-purple"> - </div></el-col>
                  <el-col :span="7" class='flex-display'><div class="grid-content bg-purple">{{OrderStatusArray[formModel.batchOrderStatus]}}</div></el-col>
                </el-row>
            </el-card>
        </div>
        <!-- Batch Push -->
        <div v-else>
            <el-card no-body border-variant="info" :header="$t('orderBatchModal.continue_push')" align="left">
                <el-row  v-for="pushOrder in modalOrderData.batchOrder" v-bind:key="pushOrder.id">
                  <el-col :span="4" class="flex-display"><i :class="orderFinished.includes(pushOrder.status) ? 'el-icon-success': 'el-icon-error'"></i></el-col>
                  <el-col :span="10" class="flex-display"><div class="grid-content bg-purple">{{pushOrder.id}}</div></el-col>
                  <el-col :span="10" class='flex-display'><div class="grid-content bg-purple">{{OrderStatusArray[pushOrder.status]}}</div></el-col>
                </el-row>
            </el-card>
        </div>
      </div>
      <!-- Push -->
      <div v-else>
        <el-card no-body border-variant="info" :header="$t('orderBatchModal.continue_push')" align="left">
          <el-col :span="12" class="flex-display"><div class="grid-content bg-purple">{{modalOrderData.selectedOrder.id}}</div></el-col>
          <el-col :span="12" class='flex-display'><div class="grid-content bg-purple">{{modalOrderData.selectedOrder.status}}</div></el-col>
        </el-card>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="onOk" >{{$t('orderBatchModal.' + modalOrderData.okTitle.toLowerCase().replace(' ', '_'))}}</el-button>
        <el-button @click="modalOrderData.show=false">{{$t('orderBatchModal.cancel')}}</el-button>
      </div> 
    </el-dialog>
  </div>
</template>

<script>
  import {editWithdrawOrder, pushWithdrawOrder} from '@/api/merchant'
  export default {
    name: 'OrderBatchModal',
    data() {
      return {
        loading: false,
        formModel: {
            batchOrderStatus: null,
            batchOrderNotes: null
        },
        batchOrderNotesCount: 50,
        batchOrderNotesRemaining: 50,
        rules: {
          batchOrderStatus: [
            { required: true, message: this.$t('orderBatchModal.please') + ' ' + this.$t('orderBatchModal.select_order_status'), trigger: 'change' }
          ],
          batchOrderNotes: [
            { required: true, message: this.$t('orderBatchModal.please') + ' ' + this.$t('orderBatchModal.enter_notes'), trigger: 'change' }
          ]
        },
        orderFinished: [2,3,4] /* 2 - Success, 3 - Manual Success, 4 - Invalid */
      }
    },
    props: {
      modalOrderData: Object,
      orderStatus: Number
    },
    methods: {
      onOk(){
        switch (this.modalOrderData.action) {
          case 'Batch Assign':
            let isValid = false

            this.$refs['orderWithdrawForm'].validate((valid) => {
                if(valid) {
                    isValid = true;
                }
            })

            if(isValid) {
              this.modalOrderData.batchOrder.forEach(order => {
                if(!this.orderFinished.includes(order.status)) {
                  let data = {order_id: order.id, status: this.formModel.batchOrderStatus, notes: this.formModel.batchOrderNotes, operating_time: null}
                  editWithdrawOrder(data).then(res => {
                    if (res.status === 0) {
                        this.$emit('ok')
                        this.$message({message: this.$t('orderBatchModal.update_success') + `${data.order_id}`, type: 'success'})
                    } else {
                        this.$message.error(res.msg)
                    }
                  })
                }
                order.selected = false
              });
              this.modalOrderData.show = false
            }
            break;
          case 'Batch Push':
            this.modalOrderData.batchOrder.forEach(order => {
              if(this.orderFinished.includes(order.status)) {
                let data = {order_id: order.id}
                pushWithdrawOrder(data).then(res => {
                    if (res.status === 0) {
                        this.$emit('ok')
                        this.$message({message: this.$t('orderBatchModal.update_success') + `${data.order_id}`, type: 'success'})
                    }
                })
              }
              order.selected = false
            });
            
            this.modalOrderData.show = false
            break;
          case 'Push':
            break;
        }
      },
      onBatchOrderChangeNotes() {
        if(this.formModel.batchOrderNotes){
            this.batchOrderNotesRemaining = 50 - this.formModel.batchOrderNotes.length;
        }
      },
      open() {
        this.rules.batchOrderStatus[0].message = this.$t('orderBatchModal.please') + ' ' + this.$t('orderBatchModal.select_order_status')
        this.rules.batchOrderNotes[0].message = this.$t('orderBatchModal.please') + ' ' + this.$t('orderBatchModal.enter_notes')
      },
      hidden() {
        if(this.modalOrderData.action === 'Batch Assign') {
          this.$refs['orderWithdrawForm'].resetFields();
        }
      }
    },
    computed: {
      OrderStatusArray: function() {
        return [ this.$t('orderBatchModal.pending'), 
                 this.$t('orderBatchModal.processing'), 
                 this.$t('orderBatchModal.success'), 
                 this.$t('orderBatchModal.manual_success'), 
                 this.$t('orderBatchModal.invalid'), 
                 this.$t('orderBatchModal.paying')]
      },
      getOptions() {
          let result = [];
          if(this.modalOrderData.action === 'View') {
              result.push({value: 0, label: this.$t('orderBatchModal.pending')});
              result.push({value: 1, label: this.$t('orderBatchModal.processing')});
              result.push({value: 2, label: this.$t('orderBatchModal.success')});
              result.push({value: 3, label: this.$t('orderBatchModal.manual_success')});
              result.push({value: 4, label: this.$t('orderBatchModal.invalid')});
          } else {
              result.push({value: 3, label: this.$t('orderBatchModal.manual_success')});
              result.push({value: 4, label: this.$t('orderBatchModal.invalid')});
          }
          return result;
      }
    }
  }

  export const enOrderBatchModal = {
    // General
    continue_assign: 'Do you want to continue edit the status to the following Orders?',
    continue_push: 'Do you want to continue push the Order?',
    character: 'Characters',
    batch_assign: 'Batch Assign',
    batch_push: 'Batch Push',

    // Modal
    id: 'Order ID',
    mch_id: 'Merchant',
    player_id: 'Player ID',
    account_name: 'Account Name',
    account_no: 'Account No',
    bank: 'Bank',
    amount: 'Amount',
    operator: 'Operator',
    source_card_code: 'Card Code',
    source_account_name: 'Source Account Name',
    source_account_no: 'Source Account No',
    status: 'Status',
    notify_status: 'Notify Status',
    created_at: 'Application Time',
    operating_time: 'Operating Time',
    exact_time: 'Exact Time',
    notes: 'Notes',

    // Action Link and Buttons
    confirm: 'OK',
    cancel: 'Cancel',
    update: 'Update',

    // Order Status
    pending: 'Pending',
    processing: 'Processing',
    success: 'Success',
    manual_success: 'Manual Success',
    invalid: 'Invalid',
    paying: 'Paying',

    // Notify Status
    notify_none: 'None',
    notify_success: 'Success',
    notify_failed: 'Failed',

    // Messages
    select_order_status: 'Select Order Status',
    enter_notes: 'Enter Notes',
    please: 'Please',
    update_success: 'Successfully modified Order Id '

  }

  export const zhOrderBatchModal = {
    // General
    continue_assign: '是否要继续将状态编辑为以下订单？',
    continue_push: '你想继续推动订单吗？',
    character: '人物',
    batch_assign: '批量分配',
    batch_push: '批量推送',

    // Modal
    id: '订单ID',
    mch_id: '商户',
    player_id: '玩家账号',
    account_name: '用户名',
    account_no: '户口号码',
    bank: '银行名',
    amount: '申请金额',
    operator: '操作者',
    source_card_code: '銀行卡編號',
    source_account_name: '源帐户名',
    source_account_no: '源帐号否',
    status: '订单状态',
    notify_status: '回调状态',
    created_at: '申请时间',
    operating_time: '处理时间',
    exact_time: '完成时间',
    notes: '笔记',

    // Action Link and Buttons
    confirm: '确定',
    cancel: '取消',
    update: '更新',

    // Order Status
    pending: '有待',
    processing: '处理',
    success: '成功',
    manual_success: '手动成功',
    invalid: '无效',
    paying: '支付中',

    // Notify Status
    notify_none: '未回调',
    notify_success: '回调成功',
    notify_failed: '回调失败',

    // Messages
    select_order_status: '选择订单状态',
    enter_notes: '输入笔记',
    please: '请',
    update_success: '成功修改。 订单ID'

  }
</script>

<style lang="scss" scoped>
  .flex-display {
      display: flex;
      justify-content: center
  }
</style>
